package com.shsubway.activity.com;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.rengwuxian.materialedittext.MaterialEditText;
import com.shsubway.R;
import com.shsubway.activity.manger.HomeActivity;
import com.shsubway.base.BaseActivity;
import com.shsubway.model.StaffEntity;
import com.shsubway.utils.Constant;
import com.shsubway.utils.ImageCutUtils;
import com.shsubway.utils.LocalImageDo;
import com.shsubway.utils.SPUtils;
import com.squareup.picasso.Picasso;

import java.io.File;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.UpdateListener;
import cn.bmob.v3.listener.UploadFileListener;

/**
 * 个人信息编辑界面
 */
public class MyDateActivity extends BaseActivity {

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.user_image)
    ImageView userImage;
    @BindView(R.id.show_user_name)
    TextView showUserName;
    @BindView(R.id.user_name)
    TextView userName;
    @BindView(R.id.layout_user_name)
    LinearLayout layoutUserName;
    @BindView(R.id.user_sex)
    TextView userSex;
    @BindView(R.id.layout_user_sex)
    LinearLayout layoutUserSex;
    @BindView(R.id.user_bir)
    TextView userBir;
    @BindView(R.id.layout_user_bir)
    LinearLayout layoutUserBir;
    @BindView(R.id.user_phone)
    TextView userPhone;
    @BindView(R.id.layout_user_phone)
    LinearLayout layoutUserPhone;
    @BindView(R.id.layout_user_image)
    LinearLayout layoutUserImage;
    @BindView(R.id.fab)
    FloatingActionButton fab;
    @BindView(R.id.layout_all)
    NestedScrollView layoutAll;
    @BindView(R.id.btn_out)
    Button btnOut;
    private Uri photoUri;
    boolean upimage = false;
    private int mYear;

    private int mMonth;

    private int mDay;
    StaffEntity staffEntity = null;
    Intent intent;
    Bundle bundle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_date);
        ButterKnife.bind(this);
        initView();
        initEvent();
    }

    private void initEvent() {
        toolbar.setNavigationOnClickListener(v -> {
            setResult(1);
            finish();
        });
    }

    private void initView() {
        setTitleBar(toolbar, "我的资料");
        intent = getIntent();
        bundle = intent.getExtras();
        staffEntity = (StaffEntity) bundle.getSerializable(Constant.STAFFENTITY);
        final Calendar c = Calendar.getInstance();
        mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH);
        mDay = c.get(Calendar.DAY_OF_MONTH);
        userName.setText(TextUtils.isEmpty(staffEntity.getStaff_name()) ? "未设置" : staffEntity.getStaff_name());
        showUserName.setText(TextUtils.isEmpty(staffEntity.getStaff_name()) ? "未设置" : staffEntity.getStaff_name());

        userSex.setText(staffEntity.getStaff_sex() == 0 ? "男" : "女");
        if (staffEntity.getStaff_birthday() != null) {
            userBir.setText(staffEntity.getStaff_birthday());

        }
        userPhone.setText(staffEntity.getStaff_phone());

        Picasso.with(context)
                .load(staffEntity.getStaff_img())
                .placeholder(staffEntity.getStaff_sex() == 0 ? R.mipmap.header_ic : R.mipmap.heard_ic_w)
                .error(R.mipmap.header_ic)
                .into(userImage);
    }




    @OnClick({R.id.layout_user_name, R.id.layout_user_sex, R.id.layout_user_bir, R.id.layout_user_phone, R.id.layout_user_image, R.id.fab})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.layout_user_name:
                editNicename();
                break;
            case R.id.layout_user_sex:
                showSex();
                break;
            case R.id.layout_user_bir:
                new DatePickerDialog(this, mDateSetListener, mYear, mMonth,
                        mDay).show();
                break;
            case R.id.layout_user_phone:
                //更换手机号 后续开通
                break;
            case R.id.layout_user_image:
                LocalImageDo localImageDo = new LocalImageDo(layoutAll, context);
                localImageDo.setOnClickButtonListener(new LocalImageDo.OnClickButtonListener() {
                    @Override
                    public void OnClick(View view, PopupWindow popupWindow) {
                        if (view.getId() == R.id.camara) {
                            ImageCutUtils.openCameraImage(MyDateActivity.this);
                        } else if (view.getId() == R.id.photo) {
                            ImageCutUtils.openLocalImage(MyDateActivity.this);
                        }
                        popupWindow.dismiss();
                    }
                });
                localImageDo.showPopuWindow();
                break;
            case R.id.fab:
                Log.e("ENT==", staffEntity.toString());
                staffEntity.setStaff_name(userName.getText().toString().trim());
                staffEntity.setStaff_sex((userSex.getText().toString().trim()).equals("男") ? 0 : 1);
                staffEntity.setStaff_birthday(userBir.getText().toString().trim());
                staffEntity.update(staffEntity.getObjectId(), new UpdateListener() {
                    @Override
                    public void done(BmobException e) {
                        if (e == null) {
                            toast("修改成功:");
                            setResult(1);
                            finish();
                        } else {
                            Log.e("ENT==", e.toString());
                            toast("修改失败，请稍后重试.");
                        }
                    }
                });
                break;
        }
    }

    /**
     * 更新日期
     */

    private void updateDisplay() {

        userBir.setText(new StringBuilder().append(mYear).append("-").append(

                (mMonth + 1) < 10 ? "0" + (mMonth + 1) : (mMonth + 1)).append("-").append(

                (mDay < 10) ? "0" + mDay : mDay));

    }

    /**
     * 日期控件的事件
     */

    private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {

        public void onDateSet(DatePicker view, int year, int monthOfYear,

                              int dayOfMonth) {

            mYear = year;

            mMonth = monthOfYear;

            mDay = dayOfMonth;

            updateDisplay();

        }

    };


    private void showSex() {
        new AlertDialog.Builder(this).setTitle("请选择您的性别：").
                setIcon(R.mipmap.ic_launcher).
                setSingleChoiceItems(new String[]{"男", "女"},
                        (Integer) get(Constant.USER_SEX, 0), new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                if (which == 0) {
                                    userSex.setText("男");
                                } else {
                                    userSex.setText("女");
                                }
                                dialog.dismiss();
                            }
                        }).setNegativeButton("取消", null).show();
    }

    private void editNicename() {
        //创建对话框
        Dialog dialog = new Dialog(this);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_edit, null);
        //给Dialog中的子view设置事件监听
        view.findViewById(R.id.no).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        MaterialEditText edit_user_name = (MaterialEditText) view.findViewById(R.id.edit_user_name);

        view.findViewById(R.id.login).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(edit_user_name.getText().toString().trim())) {
                    toast("姓名不能为空");
                } else {
                    userName.setText(edit_user_name.getText().toString().trim());
                    showUserName.setText(edit_user_name.getText().toString().trim());
                    dialog.dismiss();
                }
            }
        });
        dialog.setContentView(view);
        //自定义宽高（高度一般不用调整，在xml调整好就可以了，这里我只调整了宽度）
        WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
        params.width = 900;
        dialog.getWindow().setAttributes(params);
        //show之前设置返回键无效，触摸屏无效
        dialog.setCancelable(false);
        //显示对话框
        dialog.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case ImageCutUtils.GET_IMAGE_BY_CAMERA:
                //拍照
                ImageCutUtils.cropImageData(this, ImageCutUtils.imageUriFromCamera);
                break;
            case ImageCutUtils.GET_IMAGE_FROM_PHONE:
                //读取图库
                if (data == null) {
                    toast("选择图片文件出错");
                    return;
                }
                photoUri = data.getData();
                if (photoUri == null) {
                    toast("选择图片文件出错");
                    return;
                } else {
                    ImageCutUtils.cropImageData(this, photoUri);
                }

                break;
            case ImageCutUtils.CROP_IMAGE:
                //裁切图片

                if (data != null) {
                    Bundle extras = data.getExtras();
                    if (extras != null) {
                        Bitmap photo = extras.getParcelable("data");
                        userImage.setImageBitmap(photo);//mHeadImg是个Imageview
                        File file = ImageCutUtils.saveBitmap(photo, context);
                        if (file != null) {
                            //在这个地方开启上传图片
                            BmobFile bmobFile = new BmobFile(file);
                            bmobFile.uploadblock(new UploadFileListener() {
                                @Override
                                public void done(BmobException e) {
                                    if (e == null) {
                                        staffEntity.setStaff_img(bmobFile.getFileUrl());
                                        staffEntity.update(staffEntity.getObjectId(), new UpdateListener() {
                                            @Override
                                            public void done(BmobException e) {

                                                if (e == null) {
                                                    toast("上传文件成功:" + bmobFile.getFileUrl());
                                                    put(Constant.USER_IMAGE_HEADER, bmobFile.getFileUrl());

                                                } else {
                                                    toast("头像上传失败，请稍后重试.");
                                                }


                                            }
                                        });


                                    } else {
                                        toast("上传文件失败：" + e.getMessage());
                                    }
                                }

                                @Override
                                public void onProgress(Integer value) {
                                    // 返回的上传进度（百分比）
                                    Log.e("value==", value + "");
                                }
                            });


                        } else {
                            return;
                        }

                    } else {
                        return;
                    }

                } else {
                    return;
                }
                break;
        }
    }

    @OnClick(R.id.btn_out)
    public void onClick() {
        SPUtils.clear(context);
        HomeActivity.instance.finish();
        intent.setClass(context, LoginActivity.class);
        startActivity(intent);
        finish();
    }
}
